package com.qdlc.p2p.biz.service.activity;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * 活动计划环节处理器
 * @author linya
 */
public abstract class AbstractActivityPlanHandler implements ActivityPlanHandler, ApplicationContextAware{

	@SuppressWarnings("rawtypes")
	protected static ConcurrentMap<ActivityProgrammeEnum, ActivityProgrammeHandler> activityProgrammeMap = new ConcurrentHashMap<ActivityProgrammeEnum, ActivityProgrammeHandler>();
    
    @SuppressWarnings("rawtypes")
	private static void initActivityProgrammeHandler(ApplicationContext applicationContext){
    	if(activityProgrammeMap.isEmpty()){
    		Map<String, ActivityProgrammeHandler> map = applicationContext.getBeansOfType(ActivityProgrammeHandler.class);
    		for(ActivityProgrammeHandler handler: map.values()){
    			ActivityProgrammeEnum supportsProgramme = handler.supportsProgramme();
    			if(activityProgrammeMap.containsKey(supportsProgramme)){
    				ActivityProgrammeHandler constainedHandler = activityProgrammeMap.get(supportsProgramme);
    				String handlerName = handler.getClass().getName();
    				String constainedHandlerName = constainedHandler.getClass().getName();
    				throw new IllegalArgumentException(handlerName + " and " + constainedHandlerName + " has set a same supportsProgramme!");
    			}
    			activityProgrammeMap.put(supportsProgramme, handler);
    		}
    	}
    }
	
    @SuppressWarnings("rawtypes")
	public static ActivityProgrammeHandler getActivityProgrammeHandler(ActivityProgrammeEnum programmeEnum){
    	return activityProgrammeMap.get(programmeEnum);
    }
    
	@Override
	public Class<? extends ActivityPlanHandler> getActivityPlanHandlerClass() {
		return this.getClass();
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		initActivityProgrammeHandler(applicationContext);
	}
    
}
